/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xstgongyi.eduaid.common.PageHelper;
import org.xstgongyi.eduaid.dataobject.VolunteerDO;
import org.xstgongyi.eduaid.manager.VolunteerManager;
import org.xstgongyi.eduaid.bo.Gender;

/**
 * @author oldcrane<br/>
 * @created 2019-04-17
 */
@Service
public class VolunteerServiceImpl implements VolunteerService {

	@Autowired
	private VolunteerManager volunteerManager;

	@Override
	public void insert(VolunteerDO volunteer) {
		if (null == volunteer.getAnonymous()) {
			volunteer.setAnonymous(false);
		}
		if (null == volunteer.getGender()) {
			volunteer.setGender(Gender.unknown);
		}

		LocalDateTime now = LocalDateTime.now();
		volunteer.setGmtCreated(now);
		volunteer.setGmtUpdated(now);
		volunteerManager.insert(volunteer);
	}

	@Override
	public void update(VolunteerDO volunteer) {
		volunteer.setGmtUpdated(LocalDateTime.now());
		volunteerManager.update(volunteer);
	}

	@Override
	public VolunteerDO getById(Integer id) {
		VolunteerDO volunteer = (null == id ? null : volunteerManager.getById(id));
		return volunteer;
	}

	@Override
	public List<VolunteerDO> listAll() {
		return volunteerManager.listAll();
	}

	@Override
	public List<VolunteerDO> listPage(String keyword, int pageNumber, int pageSize) {
		Map<String, Object> condition = new HashMap<>();
		pageNumber = pageNumber > 0 ? pageNumber : 1; // 缺省为第一页
		pageSize = pageSize > 0 ? pageSize : 20; // 缺省一页20条记录
		int offset = PageHelper.calcOffset(pageNumber, pageSize);
		condition.put("offset", offset);
		condition.put("limit", pageSize);
		keyword = null == keyword ? "" : keyword.trim();
		if (keyword.length() > 0) {
			condition.put("keyword", "%" + keyword + "%");
		}

		List<VolunteerDO> volunteers = volunteerManager.listPage(condition);
		return volunteers;
	}

	@Override
	public int countTotal(String keyword) {
		Map<String, Object> condition = new HashMap<>();
		keyword = null == keyword ? "" : keyword.trim();
		if (keyword.length() > 0) {
			condition.put("keyword", "%" + keyword + "%");
		}
		return volunteerManager.countTotal(condition);
	}

}
